import 'package:dio/dio.dart';
import 'package:fsharing/core/models/order_list.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class OrderListModel extends ViewModel {
  final Api api;
  final int storeId;
  final int index;
  final List<Order> _list = [];
  String _errorMessage;
  OrderList _orderList;

  OrderListModel(this.api, this.storeId, this.index) : super() {
    _initData();
  }

  List<Order> get list => _list;

  String get errorMessage => _errorMessage;

  OrderList get orderList => _orderList;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      // 转换一下 tab index 为 status
      int status = index;
      status++;
      if (status == 4) status = 0;
      // 获取数据
      _orderList = await api.orderList(storeId, status, 0, cancelToken);
      _list.clear();
      _list.addAll(_orderList.model.content);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> refreshData() async {
    try {
      // 转换一下 tab index 为 status
      int status = index;
      status++;
      if (status == 4) status = 0;
      // 获取数据
      _orderList = await api.orderList(storeId, status, 0, cancelToken);
      _list.clear();
      _list.addAll(_orderList.model.content);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      // 转换一下 tab index 为 status
      int status = index;
      status++;
      if (status == 4) status = 0;
      // 获取数据
      _orderList = await api.orderList(storeId, status, _orderList.model.number + 1, cancelToken);
      _list.addAll(_orderList.model.content);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
